<template>
  <div class="scaner" ref="scaner">
    <van-nav-bar
      title="扫一扫"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      style="background-color: #081c33;"
    />
    <div class="cover">
      <p class="line"></p>
      <span class="square top left"></span>
      <span class="square top right"></span>
      <span class="square bottom right"></span>
      <span class="square bottom left"></span>
      <p class="tips">将二维码放入框内，即可自动扫描</p>
    </div>
   <video 
      class="source"
      ref="video"
      id="video"
      :width="videoWH.width"
      :height="videoWH.height"
       autoplay playsinline
       autofocus
      :controls="true" ></video>
    <canvas id="canvas"  :width="videoWH.width"
      :height="videoWH.height" ref="canvas" />
  </div>
</template>

<script>
import jsQR from 'jsqr';
import { userStore } from "../../stores/user.ts";
import { ElMessageBox, ElMessage } from "element-plus";

export default {
  name: 'scaner',
  props: {
    // 使用后置相机
    useBackCamera: {
      type: Boolean,
      default: true,
    },
    // 扫描识别后停止
    stopOnScaned: {
      type: Boolean,
      default: true,
    },
    drawOnfound: {
      type: Boolean,
      default: true,
    },
    // 线条颜色
    lineColor: {
      type: String,
      default: "red",
    },
    // 线条宽度
    lineWidth: {
      type: Number,
      default: 2,
    },
    // 视频宽度
    videoWidth: {
      type: Number,
      default: window.innerWidth,
    },
    // 视频高度
    videoHeight: {
      type: Number,
      default: window.innerHeight,
    },
    responsive: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      decodedContent: null,
    videoStream: null,
    boundingBox: null, // 新增属性
     showPlay: false,
      showBanner: true,
      opacity: 0,
      User_Code: null,
      Interface_Code: null,
      user: null,
      user:null,
      t1: null,
      t2: null,
      t3: null,
      t4: null,
      ts4: null,
      sx:null
    };
  },
  created() {
    this.user = userStore();
    this.User_Code = JSON.parse(sessionStorage.getItem("UserInfo")).sUser_Code;
    this.Interface_Code = sessionStorage.getItem("item");
  },
  mounted() {
    // this.initQuagga();
    this.startCamera();
     this.$refs.video.focus();
    //  this.canvas = this.$refs.canvas.getContext("2d")
  },
  computed: {
    videoWH() {
      return { width: this.videoWidth * 0.7, height: this.videoHeight };
    },
  },
  methods: {
    startCamera() {
      try {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // this.previousCode = null;
        // this.parity = 0;
        const facingMode = this.useBackCamera
          ? { exact: "environment" }
          : "user";
        const handleSuccess = (stream) => {
          this.$refs.video.srcObject = stream;
          const playPromise = this.$refs.video.play();
          playPromise.then(() => {
            this.$refs.video.focus();
           this.scanQRCode();
          });
          this.$refs.video.focus();
        };
        navigator.mediaDevices
          .getUserMedia({
            video: {
               facingMode,
             width: { min: 640},
              height: { min:480},
              frameRate: 600,
              focusMode: "continuous",
              focusDistance: { exact: 10000 },
            },
          })
          .then(handleSuccess)
          .catch((error) => {
            this.$emit("error-captured", error);
          });
      }
       
      } catch (error) {
        console.error("无法访问摄像头", error);
      }
    },
   
    scanQRCode() {
      const video = this.$refs.video;
      // const canvas = this.$refs.canvas;
      const tick = () => {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
        const canvasElement = document.createElement('canvas');
        const canvas = canvasElement.getContext('2d');
        canvasElement.height = this.$refs.video.videoHeight;
        canvasElement.width = this.$refs.video.videoWidth;
        canvas.drawImage(this.$refs.video, 0, 0, canvasElement.width, canvasElement.height);
        const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
        const code = jsQR(imageData.data, imageData.width, imageData.height, {
          inversionAttempts: 'dontInvert',
        });
          if (code) {
            this.drawBox(code.location);
      this.found(code.data);
            this.decodedContent = code.data;
            console.log("二维码识别结果:", code.data);
             console.log("二维码识别结果:", code);
       var keyValue = code.data.split("&");
        console.log(keyValue);
        var obj = {};
        for (var i = 0; i < keyValue.length; i++) {
          //循环分割挂过后的地址
          var item = keyValue[i].split("=");
          var key = item[0];
          var value = item[1];
          obj[key] = value;
        }
        console.log("nnm", obj.Check_No);
        axios
          .post(
            window.globalUrl.server + "Service.asmx/Get_CheckSub_Data",
            JSON.stringify({
              User_Code: this.User_Code,
              Interface_Code: this.Interface_Code,
              Check_No: obj.Check_No,
            })
          )
          .then((res) => {
            console.log(res);
            if (res.data.RltCode == 1) {
              this.user.Get_CheckSub_Data = JSON.parse(res.data.RltData);
              sessionStorage.setItem(
                "data",
                JSON.stringify(JSON.parse(res.data.RltData))
              );
              sessionStorage.removeItem("wd");
              sessionStorage.removeItem("t1");
              sessionStorage.removeItem("t2");
              sessionStorage.removeItem("t3");
              sessionStorage.removeItem("t4");
              sessionStorage.removeItem("ts4");
              sessionStorage.removeItem("sx");
              this.user.jkwd = [];
              this.user.tableData1 = [];
              this.user.tableData2 = [];
              this.user.tableData3 = [];
              this.user.tableData4 = [];
              this.user.tableDatas4 = [];
              this.user.tableDatasx = [];
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueInHoss",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.t1 = JSON.parse(res.data.RltData);
                    this.t1 = this.t1.map((item) => ({
                      date1: item["Hos_InDate"],
                      date2: item["Hos_OutDate"],
                      date3: item["Hos_Cause"],
                      date4: item["Hos_Group"],
                      date5: item["Hos_No"],
                    }));
                    this.user.tableData1 = this.t1;
                    sessionStorage.setItem("t1", JSON.stringify(this.t1));
                  }
                });
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueJws_Sss",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立狗", JSON.parse(res.data.RltData));
                    this.sx = JSON.parse(res.data.RltData);
                    this.sx = this.sx.map((item) => ({
                      date1: item["Jws_qzrq"],
                      date2: item["Jws_mc"],
                    }));
                    this.user.tableDatasx = this.sx;
                    sessionStorage.setItem("sx", JSON.stringify(this.sx));
                  }
                });

              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueHomeHoss",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.t2 = JSON.parse(res.data.RltData);
                    this.t2 = this.t2.map((item) => ({
                      date1: item["Hos_InDate"],
                      date2: item["Hos_OutDate"],
                      date3: item["Hos_Cause"],
                      date4: item["Hos_Group"],
                      date5: item["Hos_No"],
                    }));
                    this.user.tableData2 = this.t2;
                    sessionStorage.setItem("t2", JSON.stringify(this.t2));
                  }
                });

              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueInoculs",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.t3 = JSON.parse(res.data.RltData);
                    this.t3 = this.t3.map((item) => ({
                      name: item["Ino_Name"],
                      date1: item["Ino_Date"],
                      date2: item["Ino_Group"],
                    }));
                    this.user.tableData3 = this.t3;
                    sessionStorage.setItem("t3", JSON.stringify(this.t3));
                  }
                });
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueUseMedis",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Check_No: this.user.Get_CheckSub_Data.Check_No,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.ts4 = JSON.parse(res.data.RltData);
                    this.user.tableDatas4 = this.ts4.map((item) => ({
                      name: item["Medi_Name"],
                      date1: item["Medi_UseName"],
                      date1_id: item["Medi_Use"],
                      date2: item["Medi_freqName"],
                      date2_id: item["Medi_freq"],
                      date3: item["Medi_EachDose"],
                      date4: item["Medi_EachDoseUnit"],
                      date5: item["Medi_DoseUnitName"],
                      date5_id: item["Medi_DoseUnit"],
                      date6: item["Medi_UseDate"],
                      date7: item["Medi_UseDateUnitName"],
                      date7_id: item["Medi_UseDateUnit"],
                      date8: item["Medi_MedicineYieldName"],
                      date8_id: item["Medi_MedicineYield"],
                      // date9: item["Medi_Sugg"],
                      // date9_id: item["Medi_TypeID"],
                    }));
                    sessionStorage.setItem(
                      "ts4",
                      JSON.stringify(this.user.tableDatas4)
                    );
                    this.user.tableData4 = this.user.tableDatas4.map(
                      (item) => ({
                        name: item["name"],
                        date1: item["date1"],
                        date1_id: item["date1_id"],
                        date2:
                          item["date2"] +
                          item["date3"] +
                          "次；1次" +
                          item["date4"] +
                          item["date5"],
                        date2_id: item["date2_id"],
                        date3: item["date3"],
                        date4: item["date6"] + item["date7"],
                        dates4: item["date4"],
                        date5: item["date5"],
                        date5_id: item["date5_id"],
                        date6: item["date6"],
                        date7: item["date7"],
                        date7_id: item["date7"],
                        date8: item["date8"],
                        date8_id: item["date8_id"],
                        // date9: item["date9"],
                        // date9_id: item["date9_id"],
                      })
                    );
                    sessionStorage.setItem(
                      "t4",
                      JSON.stringify(this.user.tableData4)
                    );
                  }
                });
                 this.stopCamera();
              this.$router.replace("/jkwd");
            } else {
              if (res.data.RltCode == 0) {
                ElMessage.error(res.data.RltMsg);
              }
              sessionStorage.removeItem("t1");
              sessionStorage.removeItem("t2");
              sessionStorage.removeItem("t3");
              sessionStorage.removeItem("t4");
              sessionStorage.removeItem("ts4");
              sessionStorage.removeItem("sx")
              this.user.tableData1 = [];
              this.user.tableData2 = [];
              this.user.tableData3 = [];
              this.user.tableData4 = [];
              this.user.tableDatas4 = [];
              this.user.tableDatasx = [];
              // this.$router.replace("/jkwd");
            }
          })
          .catch((eorro) => {
            sessionStorage.removeItem("t1");
            sessionStorage.removeItem("t2");
            sessionStorage.removeItem("t3");
            sessionStorage.removeItem("t4");
            sessionStorage.removeItem("ts4");
             sessionStorage.removeItem("sx")
            this.user.tableData1 = [];
            this.user.tableData2 = [];
            this.user.tableData3 = [];
            this.user.tableData4 = [];
            this.user.tableDatas4 = [];
             this.user.tableDatasx = [];
            //  this.$router.replace("/jkwd");
          });
            // 停止扫描，或者你可以根据需要继续扫描
            // this.stopCamera();
          }
        }
        requestAnimationFrame(tick);
      };

      tick();
      
    },

     drawLine(begin, end) {
      this.canvas.beginPath();
      this.canvas.moveTo(begin.x, begin.y);
      this.canvas.lineTo(end.x, end.y);
      this.canvas.lineWidth = this.lineWidth;
      this.canvas.strokeStyle = this.lineColor;
      this.canvas.stroke();
    },
    // 画框
    drawBox(location) {
      if (this.drawOnfound) {
        this.drawLine(location.topLeftCorner, location.topRightCorner);
        this.drawLine(location.topRightCorner, location.bottomRightCorner);
        this.drawLine(location.bottomRightCorner, location.bottomLeftCorner);
        this.drawLine(location.bottomLeftCorner, location.topLeftCorner);
      }
    },
drawLine1(start, end) {
  this.canvas.beginPath();
  this.canvas.moveTo(start[0], start[1]);
  this.canvas.lineTo(end[0], end[1]);
  this.canvas.lineWidth = 2;
  this.canvas.strokeStyle ="red";
  this.canvas.stroke();
},

// 画框
drawBox1(location) {
  if (this.drawOnfound) {
    // 假设 location 是一个包含四个点的数组，每个点是一个 [x, y] 坐标对
        this.drawLine1(location[0], location[1]); // 第一条边
        this.drawLine1(location[1], location[2]); // 第二条边
        this.drawLine1(location[2], location[3]); // 第三条边
        this.drawLine1(location[3], location[0]); // 第四条边
  }
},
    
     found(code) {
      if (this.previousCode !== code) {
        this.previousCode = code;
        this.parity = 0; // 重置计数器
      } else {
        this.parity += 1;
        if (this.parity >= 2) {
          this.parity = 0;
          this.$emit("code-scanned", code);
        }
      }
    },
    onClickLeft(){
     this.$router.replace("/jkwd");
    },
    stopCamera() {
      if (this.$refs.video && this.$refs.video.srcObject) {
        //  Quagga.stop()
        this.$refs.video.srcObject.getTracks().forEach((t) => t.stop());
      }
    },
  },
  beforeDestroy() {
    // Quagga.stop()
    this.stopCamera();
  },
};
</script>
<style scoped>
.scaner {
  position: fixed;
  width: 100%;
  height: 100%;
  height: -webkit-calc(100%);
  height: -moz-calc(100%);
  height: -ms-calc(100%);
  height: -o-calc(100%);
  height: calc(100%);
}
#canvas {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  /* transform: translate(-50%,-50%); */
}
#video {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
}
.scaner .banner {
  width: 340px;
  position: absolute;
  top: 16px;
  left: 50%;
  margin-left: -170px;
  background: #fa74a2;
  border-radius: 8px;
  box-sizing: border-box;
  padding: 12px;
  opacity: 0.9;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
}
.scaner .banner .text {
  padding: 0;
  margin: 0;
  color: #ffffff;
  font-size: 12px;
  text-align: justify;
  text-align-last: left;
}
.scaner .banner .close_icon {
  display: inline-block;
  height: 24px;
  width: 24px;
  background: url("../assets/close.png") no-repeat center;
  background-size: auto 100%;
  position: absolute;
  right: 8px;
  top: 8px;
}
.scaner .cover {
  height: 220px;
  width: 220px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0.5px solid #999999;
  z-index: 1111;
}
.scaner .cover .line {
  width: 200px;
  height: 1px;
  margin-left: 10px;
  background: #5f68e8;
  background: linear-gradient(
    to right,
    transparent,
    #5f68e8,
    #0165ff,
    #5f68e8,
    transparent
  );
  position: absolute;
  -webkit-animation: scan 1.75s infinite linear;
  -moz-animation: scan 1.75s infinite linear;
  -ms-animation: scan 1.75s infinite linear;
  -o-animation: scan 1.75s infinite linear;
  animation: scan 1.75s infinite linear;
  -webkit-animation-fill-mode: both;
  -moz-animation-fill-mode: both;
  -ms-animation-fill-mode: both;
  -o-animation-fill-mode: both;
  animation-fill-mode: both;
  border-radius: 1px;
}
.scaner .cover .square {
  display: inline-block;
  height: 20px;
  width: 20px;
  position: absolute;
}
.scaner .cover .square.top {
  top: 0;
  border-top: 1px solid #5f68e8;
}
.scaner .cover .square.left {
  left: 0;
  border-left: 1px solid #5f68e8;
}
.scaner .cover .square.bottom {
  bottom: 0;
  border-bottom: 1px solid #5f68e8;
}
.scaner .cover .square.right {
  right: 0;
  border-right: 1px solid #5f68e8;
}
.scaner .cover .tips {
  position: absolute;
  bottom: -48px;
  width: 100%;
  font-size: 14px;
  color: #ffffff;
  opacity: 0.8;
}
@-webkit-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-moz-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-o-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
</style>